import React, { Component } from 'react'
import { connect } from 'react-redux'
import { EventCenter } from '@utils/Global'
import { FOOTER_SHOW_TIME } from '@utils/config'
import ReplayPlayer from '@utils/ReplayPlayer'
import PlayController from '@utils/PlayController'
import { ReplayAction } from '@act'
const { toggleShowType } = ReplayAction


class ToQaBtn extends Component {
  showBtnTimer = null
  clickBtn = () => {
    const { dispatch, showEnd } = this.props
    dispatch(toggleShowType('qaScreen', true))
    if (!showEnd) {
      ReplayPlayer.pause()
      PlayController.stop()
    }
  }
  stopTimer() {
    this.showBtnTimer && clearTimeout(this.showBtnTimer)
  }
  startTimer() {
    const { dispatch } = this.props
    this.stopTimer()
    dispatch(toggleShowType('toQaBtn', true))
    this.showBtnTimer = setTimeout(() => {
      dispatch(toggleShowType('toQaBtn', false))
    }, FOOTER_SHOW_TIME)
  }
  handleClickSwiper = () => {
    this.startTimer()
  }
  handleAudioEnd = () => {
    const { dispatch } = this.props
    this.stopTimer()
    dispatch(toggleShowType('toQaBtn', true))
  }
  componentDidMount() {
    EventCenter.addListener('click_swiper', this.handleClickSwiper)
    EventCenter.addListener('audio_ended', this.handleAudioEnd)
  }
  componentWillUnmount() {
    EventCenter.removeListener('click_swiper', this.handleClickSwiper)
    EventCenter.removeListener('audio_ended', this.handleAudioEnd)
  }
  render() {
    const { show, showEnd } = this.props
    const className = showEnd ? 'to_qa_btn up' : 'to_qa_btn down'
    return (
      <div onClick={this.clickBtn} className={className} style={{display: show ? 'block' : 'none'}}>
       查看课程Q&A
       <img className="to_qa_btn_icon" src={require('@images/replay_to_qa_icon.png')} alt=""/>
      </div>
    )
  }
}

const mapState = (state) => {
  return {
    show: state.ReplayState.showType.toQaBtn,
    showEnd: state.ReplayState.showType.endBtn
  }
}

export default connect(mapState)(ToQaBtn)
